package com.mishow.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils.TruncateAt;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.alibaba.fastjson.JSON;
import com.amap.api.services.core.LatLonPoint;
import com.android.volley.Request;
import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.activity.photo.AlbumActivity;
import com.mishow.activity.photo.GalleryActivity;
import com.mishow.adapter.photo.GridAdapter;
import com.mishow.bean.HotSearchBean;
import com.mishow.bean.photo.ImageItem;
import com.mishow.log.MyLog;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.request.core.Response;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.UploadImageFileResponse;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.Constants;
import com.mishow.utils.FileUtil;
import com.mishow.utils.ToastUtil;
import com.mishow.utils.photo.Bimp;
import com.mishow.utils.photo.PublicWay;
import com.mishow.utils.photo.Res;
import com.mishow.volley.http.mine.MultipartRequestParams;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.volley.http.request.MultipartRequest;
import com.mishow.widget.AdjustLayout;
import com.mishow.widget.MyGridView;
import com.mishow.widget.UploadImageDialog;

/**
 * 
 * 作者：wei.miao <br/>
 * 描述：精选发布
 */
public class SelectReleaseActivity extends BaseActivity {

	private Button btn_back;
	private TextView title_tv;
	private TextView title_right;
	
	private EditText edit_select_name;
	
	
	/** 平面拍摄数据 **/
	private List<HotSearchBean> labelDatas = new ArrayList<HotSearchBean>();
	
	
	/** 标签AdjustLayout **/
	private AdjustLayout adjust_label_layout;
	//-------------------------------------------
	private MyGridView noScrollgridview;
	private GridAdapter adapter;
	public static Bitmap bimap;
	
	/**
	 * 上传图片对话框
	 **/
	private UploadImageDialog uploadImageDialog;
	/**
	 * 拍照的图片文件
	 **/
	private File cameraFile;
	
	private SharedPreferencesUtil mShPreferencesUtil;
	
	public static void intoActivity(Context context){
		
		Intent intent = new Intent(context,SelectReleaseActivity.class);
		context.startActivity(intent);
		
	}
	@Override
	protected void initData() {
		
		Res.init(this);
		bimap = BitmapFactory.decodeResource(getResources(),R.drawable.icon_dynarmic_select);
		PublicWay.activityList.add(this);
		
		for (int i = 0; i < 5; i++) {
			
			HotSearchBean hot = new HotSearchBean();
		    if (i % 2 == 0) {
		    	hot.setGhwName("运动系列");
			}else{
				hot.setGhwName("婚纱系列");
			}
		    labelDatas.add(hot);
		}
		
		mShPreferencesUtil = new SharedPreferencesUtil(mContext);
		
	}

	@Override
	protected void initView(Bundle savedInstanceState) {
		
		setContentView(R.layout.activity_mishowselect);
		btn_back =  (Button)findViewById(R.id.btn_back);
		title_tv = (TextView)findViewById(R.id.title_tv);
		title_right = (TextView)findViewById(R.id.title_right);
		
		
		edit_select_name = (EditText)findViewById(R.id.edit_select_name);
		
		adjust_label_layout = (AdjustLayout)findViewById(R.id.adjust_label_layout);
		
		noScrollgridview = (MyGridView) findViewById(R.id.noScrollgridview);
	}

	@Override
	protected void setAttribute() {
		
		title_tv.setText("精选");
		title_right.setVisibility(View.VISIBLE);
		title_right.setText("发布");
		title_right.setTextColor(getResources().getColor(R.color.rb_select));
		title_right.setOnClickListener(onClickListener);
		
		btn_back.setOnClickListener(onClickListener);
		
		filledPlaneDatas();
		
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		adapter.update();
		noScrollgridview.setAdapter(adapter);
		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == Bimp.tempSelectBitmap.size()) {
					MyLog.d("arg2==" + arg2);
					showUploadImageDialog();
				} else {
					Intent intent = new Intent(SelectReleaseActivity.this,GalleryActivity.class);
					intent.putExtra("position", "4");
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});
		
	}
	
	private OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_back:
				finish();
				break;
			case R.id.title_right:
				if (edit_select_name.getText().toString().length() < 1) {
					ToastUtil.show(mContext, "请输入系列名称");
				} else {
					// 请求服务端接口
					if (Bimp.tempSelectBitmap != null && Bimp.tempSelectBitmap.size() > 0) {
						
						doUploadImage(Bimp.tempSelectBitmap);
					}else{
						ToastUtil.show(mContext, "请上传精选图片");
					}
				}
				break;
			default:
				break;
			}
			
		}
	};
	
	/**
	 * 填充显示标签
	 */
	private void filledPlaneDatas() {
		
		for (final HotSearchBean bean : labelDatas) {
			View view = LayoutInflater.from(this).inflate(R.layout.item_hot_search, null);
			CheckBox textView = (CheckBox) view.findViewById(R.id.hot_search_text);
			textView.setText(bean.getGhwName());
			textView.setSingleLine(true);
			textView.setEllipsize(TruncateAt.MIDDLE);
			textView.setOnCheckedChangeListener(onCheckedChangeListener);
			if (textView.isChecked()) {
				textView.setBackgroundResource(R.drawable.shape_selectitem_press);
			}
			adjust_label_layout.addView(view);
		}
	}
	
	private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            
        	/*if (isChecked) {
                mStrings.add(s);
            } else {
                mStrings.remove(s);
            }*/
        	compoundButton.setChecked(isChecked);
            refreshSelectedCount();

        }
    };

    // refresh标题栏显示的选择数
    private void refreshSelectedCount() {
        //int total = mStrings.size();
        //mTitleRight.setText("已选 (" + total + ")");
    }
    
    /**
	 * 选择操作图片dialog
	 */
	private void showUploadImageDialog() {

		if (uploadImageDialog == null) {
			uploadImageDialog = new UploadImageDialog(this, R.style.ShareDialog);

			// 相机
			uploadImageDialog
					.setOnTakePhotoClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							startActivityForResult(openCameraIntent, Constants.REQUEST_CODE_TAKE_PHOTO);
						}
					});

			// 相册
			uploadImageDialog
					.setOnPickPhotoClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {

							Intent intent = new Intent(mContext,AlbumActivity.class);
							intent.putExtra(Constants.IMAGE_RELEASE_TYPE, Constants.IMAGE_RELEASE_TYPE_SELECT);
							//startActivityForResult(intent,Constants.IMAGE_TYPE_RELEASE_REQUEST_CODE);
							startActivity(intent);
							overridePendingTransition(R.anim.activity_translate_in,R.anim.activity_translate_out);
						}
					});
		}
		uploadImageDialog.show();
	}
	
	/**
     *上传图片接口
     * @param orignalFilePath
     * @param uploadFile
     */
    private void doUploadImage(ArrayList<ImageItem> uploadFile) {

        if (!AndroidUtil.isNetworkAvailable(this)) { // 无网络连接
            ToastUtil.show(mContext, getString(R.string.no_connector));
            return;
        }
        showProgress("", "", true);
        MultipartRequestParams params = new MultipartRequestParams();
        for (int i = 0; i < uploadFile.size(); i++) {
			
        	String file = uploadFile.get(i).imagePath;
        	params.put("imgFile", new File(file));
		}
        
        String url = HttpUrlConstant.getPostUrl(this,HttpUrlConstant.SAVE_UPLOAD_IMG);
        
        OnResponseListener<JSONObject> listener = new OnResponseListener<JSONObject>(this) {
            @Override
            public void onSuccess(JSONObject response) {
            	
            	UploadImageFileResponse bean = (UploadImageFileResponse)JSON.parseObject(response.toString(),UploadImageFileResponse.class);
                if (bean != null) {
					//ToastUtil.show(mContext, bean.getBody().getMessage());
					doPostSelect(bean.getBody().getResult().getDataList());
				} 
            }

            @Override
            public void onError(String code, String message) {
                dismissProgress();
                ToastUtil.show(mContext, message);
            }

            @Override
            public void onCompleted() {
                dismissProgress();
            }
        };
        executeRequest(mContext, new MultipartRequest(url, params, listener, listener));
    }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case Constants.REQUEST_CODE_TAKE_PHOTO:
				if (Bimp.tempSelectBitmap.size() < 9) {
					handleFromCamera(data);
				}
				break;
			default:
				break;
			}
		}
	}
    
    /**
	 * 相机拍照获取数据
	 */
	private void handleFromCamera(Intent data) {
		
		String fileName = String.valueOf(System.currentTimeMillis());
		Bitmap bm = (Bitmap) data.getExtras().get("data");
		
		cameraFile = new File(FileUtil.getStructureDirs(FileUtil.IMAGE_PATH),fileName);
		ImageItem takePhoto = new ImageItem();
		takePhoto.setBitmap(bm);
		takePhoto.setImagePath(cameraFile.getAbsolutePath());
		Bimp.tempSelectBitmap.add(takePhoto);
		
	}
	
	@Override
	protected void onRestart() {
		adapter.notifyDataSetChanged();
		super.onRestart();
	}
	
	/**
	 * 发布精选信息
	 */
	private void doPostSelect(ArrayList<String> images) {

		if (!AndroidUtil.isNetworkAvailable(mContext)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", false);
		Map<String, String> params = new HashMap<String, String>();
		params.put("userId", mShPreferencesUtil.getUserId());// 当前登陆用户ID
		params.put("Id", 0+"");// 相册ID(增加图片时必填)
		params.put("photoName",edit_select_name.getText().toString());// 精选名称(创建时必填)
		params.put("imageStr", images.toString()); // 图片字符

		Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(mContext,HttpUrlConstant.SAVE_SELECT_PHOTO);
		OnResponseListener<Response> listener = new OnResponseListener<Response>(mContext) {

			@Override
			public void onSuccess(Response response) {

				ToastUtil.show(mContext, response.getBody().getMessage());
				//跳转至我的精选页面
				MySelectActivity.intoActivity(mContext);
				mContext.finish();
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<Response>(Request.Method.POST,
				postUrl, Response.class, listener, listener)
				.setParams(lastParams));

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			onBack();
		}
		return true;
	}

	private void onBack() {

		for (int i = 0; i < PublicWay.activityList.size(); i++) {
			if (null != PublicWay.activityList.get(i)) {
				PublicWay.activityList.get(i).finish();
			}
		}

	}
}
